// ==PREPROCESSOR==
// @name "ALBUM LIBRARY touch mod___by_Terro_Sort_Folders_by_ss"
// @version "2.1"
// @author "Vo Thanh Dat"
// ==/PREPROCESSOR==

function RGBA(r, g, b, a) {
    return (a << 24) | (r << 16) | (g << 8) | (b);
}

function RGB(r, g, b) {
    return 0xff000000 | (r << 16) | (g << 8) | (b);
}

var g_no_cover_gliph_color = 0,
    g_text_glow_color = 0,
    g_text_shadow_color = 0,
    g_backcolor = 0,
    g_cover_back_color = 0,
    g_back_shadow_color = 0,
    g_select_color = 0,
    g_select_color2 = 0,
    g_text_color = 0,
    g_color_normal_bg = 0;

var lbup = 0;
var lbdn = 0;
var x_start = 0;
var x_end = 0;
var x_delta = 0;

var DrawBitmap = true;
var Load_async = true;

var form_text = "",
    form_text_b = "",
    form_his = [],
    form_his_ = [],
    char_index = [];

ppt = {

    showwallpaper: window.GetProperty("_DISPLAY: Show Wallpaper", true),
    wallpaperblurred: window.GetProperty("_DISPLAY: Wallpaper Blurred", true),
    wallpaperblurvalue: window.GetProperty("_DISPLAY: Wallpaper Blur value", 2.00) / 1.6,
    wallpapermode: window.GetProperty("_DISPLAY: Wallpaper Mode", false),
    wallpaperpath: window.GetProperty("_DISPLAY: Default Wallpaper Path", ".\\wsh_br3tt\\jsplaylist\\images\\default.jpg"),
    wallpaperalfa: window.GetProperty("_DISPLAY: Wallpaper Alfa", 150),
    wallpaperoverlayalfa: window.GetProperty("_DISPLAY: Wallpaper Overlay Alfa", 50),
}

var brw = null;
var wpp_img_info = {
    orient: 0,
    cut: 0,
    cut_offset: 0,
    ratio: 0,
    x: 0,
    y: 0,
    w: 0,
    h: 0
};
var g_wallpaperImg = null;

var font_size = window.GetProperty("Font_Size", 25);
var font_name = window.GetProperty("Font_Name", "Segoe UI Semibold");
var font_style = window.GetProperty("Font_Style", 0);
var g_time = window.SetInterval(on_timer, window.GetProperty("TimerInterval", 64) / 2);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var WshShell = new ActiveXObject("WScript.Shell");
var htmlfile = new ActiveXObject('htmlfile');
var touch_sens = window.GetProperty("Touch_sensitivity", 25);
var scroll_step = window.GetProperty("Scroll_Step", 1);
var row_count = window.GetProperty("Row", 3);
var playlist = window.GetProperty("playlist exclusion", "");
var min_song = window.GetProperty("minimum song per group", 1);
var sorting_opt = window.GetProperty("Group Sort by (def [%album artist%]^^[%album%])", "[$directory_path(%path%)]^^[]");
var def_dblclk_act = window.GetProperty("Default Double Click Action ADD|APPLY", true);
//================================================================================================= Colors
var select_color = window.GetProperty("_COLOR: Select Color", "RGBA(0,0,0,0)"),
    select_color2 = window.GetProperty("_COLOR: Select Color 2", "RGBA(60,125,255,0)"),
    sel_alpha = window.GetProperty("_COLOR: Select FillGradRect Alpha ", 180),
    cover_back_color = window.GetProperty("_COLOR: Cover Back Color", "RGBA(0,0,0,150)"),
    back_shadow_color = window.GetProperty("_COLOR: Cover Back Shadow Color", "RGBA(100,100,100,0)"),
    text_color = window.GetProperty("_COLOR: Text Color", "RGB(200,200,210)"),
    background_color = window.GetProperty("_COLOR: Background Color", "RGB(15,15,15)"),
    text_shadow_color = window.GetProperty("_COLOR: Text Shadow Color", "RGBA(0,0,0,150)"),
    text_glow_color = window.GetProperty("_COLOR: Text Glow Color", "RGBA(200,200,210,150)"),
    text_glow_color_width = window.GetProperty("_COLOR: Text Glow Color Width", 3),
    no_cover_gliph_color = window.GetProperty("_COLOR: No Cover Gliph Color", "RGBA(200,200,210,100)"),
    load_lib_timeout = window.GetProperty("_SYS: On Start Timeout", 200),
    time_to_refresh_on_add_rem = window.GetProperty("_SYS: Timeout to Refresh on Add|Remove", 3000)
stub_image_gliph = window.GetProperty("_SYS: Stub Image Gliph", true),
    select_angle = window.GetProperty("_SYS: Select FillRect Angle", 45),
    select_angle2 = window.GetProperty("_SYS: Cover Back FillRect Angle", 45);

function get_colors() {
    if (background_color.length > 0) g_backcolor = eval(background_color);
    if (cover_back_color.length > 0) g_cover_back_color = eval(cover_back_color);
    if (back_shadow_color.length > 0) g_back_shadow_color = eval(back_shadow_color);
    if (select_color.length > 0) g_select_color = eval(select_color);
    if (select_color2.length > 0) g_select_color2 = eval(select_color2);
    if (text_color.length > 0) g_text_color = eval(text_color);
    if (text_shadow_color.length > 0) g_text_shadow_color = eval(text_shadow_color);
    if (text_glow_color.length > 0) g_text_glow_color = eval(text_glow_color);
    if (no_cover_gliph_color.length > 0) g_no_cover_gliph_color = eval(no_cover_gliph_color);
};

function on_colors_changed() {
    get_colors();
    CollectGarbage();
    window.Repaint();
};

get_colors();

var font_gliph_size = window.GetProperty("_SYS: No Cover Gliph Size", 120);
var no_cover_gliph = window.GetProperty("_SYS: No Cover Gliph", "?");

var cover_path = new RegExp("(artwork)|(cover)|(scan)|(image)");
var cover_img = "*folder*.*-*front*.*-*cover*.*-*.*".split("-");
var g_font_gliph = gdi.Font("Segoe MDL2 Assets", font_gliph_size, 0);
var g_font = gdi.Font("Segoe UI", 14, 0);
var g_font_m = gdi.Font("Segoe UI", 14, 0);
var g_font_i = gdi.Font("Segoe UI Semibold", 13, 2);
var g_font_c = gdi.Font(font_name, font_size, font_style); //================ font
var g_font_al1 = gdi.Font("Segoe UI Semibold", 14, 0);
var g_font_al2 = gdi.Font("Segoe UI Semibold", 22, 0);
var g_font_al3 = gdi.Font("Segoe UI Semibold", 16, 0);
var g_font_al4 = gdi.Font("Segoe UI Semibold", 14, 0);
var time_f = fb.CreateProfiler("time_f"),
    time_s = fb.CreateProfiler("time_s"),
    time_r = fb.CreateProfiler("time_r"),
    time_h = fb.CreateProfiler(),
    time_scroll = fb.CreateProfiler("Time delay paint");

var stub_image, cell_null, cell_null_gr;
var mouse_l_hold_f = false,
    on_form = false,
    form_text_cusor_hiden = false,
    repaint_f1 = false,
    repaint_f2 = false,
    repaint_f = true,
    repaint_a = false,
    repaint_main1 = false,
    repaint_main2 = false,
    repaint_main = true,
    hold_shift = false,
    mouse_in = false,
    main_or_form = false,
    hold_scroll = false,
    isvisible = false;

var form_text_cusor = 0,
    bold_start = 0,
    bold_end = 0,
    shift_index = 0,
    text_heigh = 0, //================== def 23 search string height
    time_reset_loadimg = 30,
    postion_load_img = 0.5,
    m_m = -1,
    max_scroll = window.Width,
    max_load_done = 0,
    ww = window.Width,
    wh = window.Height,
    m_x = 0,
    m_y = 0,
    start = 0,
    end = 0,
    start_ = 0,
    time_dl = 0;

var scroll = 0,
    scroll_ = 0,
    scroll__ = 0,
    scroll___ = 0,
    scr1 = 0,
    scroll_v = 0,
    scroll_a = 0,
    scr2 = window.Width,
    cell = Math.floor((wh - text_heigh - 12) / row_count);
//cell = cell/2;//Math.floor((wh - text_heigh - 12));
var list = [],
    list_al = [],
    list_ar = [],
    list_ge = [],
    list_dr = [],
    list_img = [];

var ex_al_idx = -1000,
    ex_length_idx = [],
    ex_length_idx_ = [],
    ex_length_idx__ = [],
    ex_length_idx___ = [],
    playlist_ex = null,
    playlist_ex_maxscr = 0,
    check_ex_old = -1,
    ex_opt = true;

window.DlgCode = 0x0081;

function get_cusor_index(x) {
    var result = form_text.length;
    while (char_index[result] > x)
        result--;
    return (result > 0) ? result : 0;
}

function refresh_char_index(gr) {
    char_index = [];
    for (var i = 0; i < form_text.length + 1; i++)
        char_index[i] = gr.EstimateLineWrap(form_text.substr(0, i), g_font, ww).toArray()[1];
}
//===========================================================================================
function on_mouse_lbtn_up(x, y, mask) {
    lbup = 1;
    lbdn = 0;
    x_start = x;
    hold_scroll = mouse_l_hold_f = false;
    scroll = Math.round(scroll / cell / 2) * cell * 2;
}
//=============================================================================================
function on_mouse_lbtn_down(x, y, mask) {
    lbup = 0;
    lbdn = 1;
    x_start = x;
    g_drag = true;
    mouse_l_hold_f = on_form = (y < text_heigh);
    mouse_l_hold = !mouse_l_hold_f;
}


function on_size() {
    if (!window.Width || !window.Height) {
        return;
    };

    ww = window.Width;
    wh = window.Height;

    def_dblclk_act = window.GetProperty("Default Double Click Action ADD|APPLY");
    ppt.wallpaperpath = window.GetProperty("_DISPLAY: Default Wallpaper Path");
    // set wallpaper
    if (fb.IsPlaying) {
        g_wallpaperImg = setWallpaperImg(ppt.wallpaperpath, fb.GetNowPlaying());
    };
    else {
        //g_wallpaperImg = null;
        g_wallpaperImg = setWallpaperImg(ppt.wallpaperpath, fb.GetNowPlaying());
    };

    //if(ww == 0 || wh == 0)
    //  return;
    var scroll_t = Math.floor(scroll / cell / 2);
    cell = Math.floor((wh - text_heigh - 12) / row_count);
    scroll____ = scroll__ = scroll_ = scroll = scroll_t * cell * 2;
    max_scroll = scroll_ + ww;
    repaint_f1 = repaint_f2;
    repaint();
}

function on_char(code) {
    time333 = (new Date()).getTime();
    if (on_form) {
        time_s.Reset();
        form_text_cusor_hiden = true;
        selected_cusor = -1;
        var coppy = false,
            paste = false,
            cut = false;
        var input = String.fromCharCode(code);
        switch (code) {
            case 13: //ENTER
                var pllist = plman.GetPlaylistItems(-1);
                for (var i in list_dr)
                    pllist.AddRange(list_dr[i].pl)
                apply_playlist(pllist);
                break;

            case 25:
                form_his.push(form_text);
                if (form_his.length > 30) form_his.shift();
                if (form_his_.length > 0) form_text = form_his_.pop() + "";
                break;
            case 26:
                form_his_.push(form_text);
                if (form_his_.length > 30) form_his.shift();
                if (form_his.length > 0) form_text = form_his.pop() + "";
                break;

            case 1: //CTRL + A
                bold_start = 0;
                bold_end = form_text.length;
                break;

            case 3: // COPPY
                (bold_start != bold_end) && htmlfile.parentWindow.clipboardData.setData('text', form_text.substring(bold_start, bold_end));
                break;

            case 24: //CUT
                (bold_start != bold_end) && htmlfile.parentWindow.clipboardData.setData('text', form_text.substring(bold_start, bold_end));
            case 8:
                save_form_his();
                if (bold_start == bold_end) {
                    form_text = form_text.substring(0, form_text_cusor - 1) + form_text.substring(form_text_cusor, 200);
                    if (form_text_cusor > 0)
                        form_text_cusor--;
                    bold_end = bold_start = form_text_cusor;
                } else {
                    form_text = form_text.substring(0, bold_start) + form_text.substring(bold_end, 200);
                    form_text_cusor = bold_start;
                    bold_end = bold_start;
                }
                break;

            case 22: //CTRL + V//PASTE
                input = htmlfile.parentWindow.clipboardData.getData('text');
                if (input == null) input = "";
            default: //CHAR
                save_form_his();
                if (char_index[form_text.length] + text_heigh >= ww - 10)
                    break;
                if (bold_start == bold_end) {
                    form_text = form_text.substring(0, form_text_cusor) + input + form_text.substring(form_text_cusor, 200);
                    form_text_cusor += input.length;
                    bold_end = bold_start = form_text_cusor;
                } else {
                    form_text = form_text.substring(0, bold_start) + input + form_text.substring(bold_end, 200);
                    form_text_cusor = bold_start + input.length;
                    bold_end = bold_start;
                }
                break;

        }
        repaint_f1 = repaint_f2;
    }
}

function save_form_his() {
    if (time_h.Time < 100)
        return;
    form_his.push(form_text);
    form_his_ = [];
    if (form_his.length > 30) form_his.shift();
    time_h.Reset();
}

function on_key_down(vkey) {
    switch (vkey) {
        case 0x25:
            if (!on_form) return;
            if (form_text_cusor > 0) {
                form_text_cusor--;
            }
            if (hold_shift) {
                bold_start = (form_text_cusor < shift_index) ? form_text_cusor : shift_index;
                bold_end = (form_text_cusor > shift_index) ? form_text_cusor : shift_index;
            } else
                bold_start = bold_end = form_text_cusor;
            break;
        case 0x27:
            if (!on_form) return;
            if (form_text_cusor < form_text.length) {
                form_text_cusor++;
            }
            if (hold_shift) {
                bold_start = (form_text_cusor < shift_index) ? form_text_cusor : shift_index;
                bold_end = (form_text_cusor > shift_index) ? form_text_cusor : shift_index;
            } else
                bold_start = bold_end = form_text_cusor;
            break;
        case 0x10:
            hold_shift = true;
            shift_index = form_text_cusor;
            break;
        case 0x11:
            break;
        case 13:

            break;
        case 40:
        case 38:

            break;
    }
    repaint_f1 = repaint_f2;
    form_text_cusor_hiden = true;
}

function on_key_up(vkey) {
    switch (vkey) {
        case 0x10:
            hold_shift = false;
            shift_index = form_text_cusor;
            break;
        case 0x11:
            hold_ctrl = false;
            break;
    }
}
//=========================================================================================== Touch mod
function on_mouse_move(x, y) {

    if (lbdn) {
        x_end = x;
        x_delta = (x_end - x_start);
        if (x < ww) {

            if (x_delta > ww / touch_sens) {
                on_mouse_wheel(1);
                x_start = x_end;
            }
            if (x_delta < -ww / touch_sens) {
                on_mouse_wheel(-1)
                x_start = x_end;
            };

        }
    }
    if (m_x == x && m_y == y)
        return;

    mouse_in = y > text_heigh;


    m_x = x;
    m_y = y;
}

function on_mouse_leave() {
    hold_scroll = mouse_hold = mouse_in = false;
    lbup = 0;
    lbdn = 0;
    repaint();
}

//=============================================================== ON PAINT//Search bar
function on_paint(gr) {
    !window.IsTransparent && gr.FillSolidRect(0, 0, ww, wh, g_backcolor);
    if (ww == 0 || wh == 0)
        return;

    if (fb.IsPlaying && g_wallpaperImg && ppt.showwallpaper) {
        gr.GdiDrawBitmap(g_wallpaperImg, 0, 0, ww, wh, 0, 0, g_wallpaperImg.Width, g_wallpaperImg.Height);
        gr.FillSolidRect(0, 0, ww, wh, g_color_normal_bg & RGBA(255, 255, 255, ppt.wallpaperalpha));
    };
    else {
        if (g_wallpaperImg && ppt.showwallpaper) {
            gr.GdiDrawBitmap(g_wallpaperImg, 0, 0, ww, wh, 0, 0, g_wallpaperImg.Width, g_wallpaperImg.Height);
            gr.FillSolidRect(0, 0, ww, wh, g_color_normal_bg & RGBA(255, 255, 255, ppt.wallpaperalpha));
        };
        else {
            gr.FillSolidRect(0, 0, ww, wh, g_color_normal_bg);
        };

    };

    repaint_f = repaint_main = true;

    if (repaint_main) {
        //fb.trace("on_paint_main : " + scroll_);
        var time_reset = (Math.abs(scroll - scroll_) > cell * 0.9);
        repaint_main = false;
        var hg = Math.floor((wh - text_heigh - 12) / row_count);
        var width_ = 0;
        var paint_continue = true;
        start = Math.max(0, Math.round(scroll_ / hg / 2 - 0.5)) * row_count;
        end = Math.min(start + Math.round(ww / hg / 2 + 1.5) * row_count, list_dr.length);
        var sss = (1 - Math.pow(0.9, time_dl / 10));
        for (var i = 0; i < list_dr.length; i++) {
            if (Math.abs(list_dr[i].i - i) * cell > 1) {
                list_dr[i].i += (i - list_dr[i].i) * sss;
                repaint();
                repaint_f1 = repaint_f2;
                if (Math.abs(list_dr[i].i - i) > 0.5)
                    time_reset = true;
                if (Math.abs(list_dr[i].i - i) < 3 && list_dr[i].al < 250)
                    list_dr[i].al = 255 * (1 - Math.abs(list_dr[i].i - i) / 3)
            }
        }
        for (var i = start; i < end; i++) {

            if (list_dr[i].al == 0 || Math.abs(list_dr[i].i - i) > row_count)
                continue;
            var x_ = Math.round((list_dr[i].i + 0.5) / row_count - 0.5) * hg * 2 - scroll_;
            var y_ = hg * ((list_dr[i].i + 0.5) % row_count) + text_heigh + 4 - 0.5 * hg;

            if (list_dr[i].alpha > 0 && !(list_dr[i].alpha >= sel_alpha && i == check(m_x, m_y))) {
                list_dr[i].alpha -= 2 * time_dl / 2;
                repaint();
            }

            list_dr[i].alpha = Math.min(list_dr[i].alpha, sel_alpha);
            (list_dr[i].alpha > 0) && gr.FillGradRect(x_ - 0.5, y_ - 3, hg * 2 + 3, hg + 3, select_angle, g_select_color | (list_dr[i].alpha << 24), g_select_color2 | (list_dr[i].alpha << 24)); //select_color

            if (list_dr[i].imgcell && list_dr[i].imgcell.Width == (cell * 2 - 3)) {
                gr.GdiAlphaBlend(list_dr[i].imgcell, x_ + 3, y_ + 1, 2 * cell - 3, cell - 3, 0, 0, cell * 2 - 3, cell - 3, list_dr[i].al);
            } else if (paint_continue && list_dr[i].img_) {
                list_dr[i].imgcell = Draw_cell(list_dr[i].img_, list_dr[i].name + "\r\n(" + list_dr[i].pl.Count + " Tracks)");
                gr.GdiAlphaBlend(list_dr[i].imgcell, x_ + 3, y_ + 1, 2 * cell - 3, cell - 3, 0, 0, cell * 2 - 3, cell - 3, list_dr[i].al);
                time_r.Reset();
                repaint();
                paint_continue = false;
                //break;
            } else if (paint_continue) {
                list_dr[i].imgcell = Draw_cell(null, list_dr[i].name + "\r\n(" + list_dr[i].pl.Count + " Tracks)");
                gr.GdiAlphaBlend(list_dr[i].imgcell, x_ + 3, y_ + 1, 2 * cell - 3, cell - 3, 0, 0, cell * 2 - 3, cell - 3, list_dr[i].al);
                time_r.Reset();
                repaint();
                paint_continue = false;
                //break;
            }
        }
        time_reset && time_r.Reset();

        var lenf_ = cell * 2 * Math.round(list_dr.length / row_count + 0.499) + ww % (cell * 2);
        var scr2_ = Math.min(Math.round(ww * ww / lenf_) + 1, ww + 20);
        if (Math.round(list_dr.length / row_count + 0.499) * (cell * 2) > ww)
            max_scroll = lenf_;
        scr1 = scroll_ / lenf_ * ww;
        scr2 += (scr2_ - scr2) * sss;
        if (scr2 < ww) {
            gr.DrawLine(0, wh - 4, ww, wh - 4, 7, 0x60000000); // scrollbar
            gr.DrawLine(scr1, wh - 4, scr1 + scr2, wh - 4, 5, 0xa0ffffff); // scrollbar
            ((scr2_ - scr2) * sss > 1) && repaint();
        }
    }
}

function on_timer(timer_id) {

    if (window.IsVisible && ww * wh > 0) {
        on_timer_();
    } else if (time_scroll.Time > 30 && max_load_done + 2 < list_dr.length) {
        main_or_form = true;
        time_scroll.Reset();
        on_timer_();
    }
    if (!window.IsVisible || ww == 0 || wh == 0)
        return;
    on_timer_();
}

var smoothness_scroll = window.GetProperty("Smoothness Scroll <|>", 12);

function on_timer_() {
    //if(!window.IsVisible || ww == 0 || wh == 0)//============= my //
    //return;  //======== my //
    var repaint_1 = false,
        repaint_2 = false,
        repaint_3 = false;
    main_or_form = !main_or_form;
    if (main_or_form) { ///////////////////////////////////////////////////////////
        if (repaint_f1 == repaint_f2) {
            repaint_f2 = !repaint_f1;
            repaint_1 = true;
        }
        if (time_f.Time > 500) {
            time_f.Reset();
            repaint_1 = true;
            form_text_cusor_hiden = !form_text_cusor_hiden;
        }
    } else { ///////////////////////////////////////////////////////////
        time_dl = time_scroll.Time;
        var delta = (1 - Math.pow(0.9, time_dl / smoothness_scroll)); // smoothness scroll time
        time_scroll.Reset();
        if (form_text_b != form_text && time_s.Time > 150) {
            time_s.Reset();
            repaint_2 = true;
            form_text_b = form_text;
            time_s.Reset();
            search(form_text);
        }
        var id = check(m_x, m_y);

        if (id > -1 && list_dr[id].alpha < 255) { //=============== repaint(stop infinity repaint) 255

            list_dr[id].alpha += 24 * time_dl / 6;
            repaint_2 = true;

        }
        if (id > -1 && list_dr[id].alpha >= sel_alpha) {
            list_dr[id].alpha += 24 * time_dl / 6;
            repaint_2 = false;
        }
        //===================================================//

        if (scroll < 0)
            scroll = 0;
        else if (scroll + ww > max_scroll)
            scroll = max_scroll - ww;

        if (Math.abs(scroll - scroll_) > 0.4) {
            scroll___ += (scroll - scroll___) * delta;
            scroll__ += (scroll___ - scroll__) * delta;
            scroll_ += (scroll__ - scroll_) * delta;
            repaint_2 = true; //true
        } else
            scroll___ = scroll__ = scroll_ = scroll;
        //ex_length_idx_
        var col_idx_s = Math.max(Math.floor(start / row_count) - 3, 0),
            col_idx_e = Math.min(Math.floor(end / row_count) + 2, ex_length_idx.length);

        var al_ex = false;
        for (var i = 0; i < ex_length_idx.length; i++) {
            if (Math.abs(ex_length_idx[i] - ex_length_idx_[i]) > 0.001) {
                ex_length_idx___[i] += (ex_length_idx[i] - ex_length_idx___[i]) * delta;
                ex_length_idx__[i] += (ex_length_idx___[i] - ex_length_idx__[i]) * delta;
                ex_length_idx_[i] += (ex_length_idx__[i] - ex_length_idx_[i]) * delta;
                al_ex = repaint_2 = true;
            } else
                ex_length_idx___[i] = ex_length_idx__[i] = ex_length_idx_[i] = ex_length_idx[i];
        }


        if (playlist_ex && Math.abs(playlist_ex.scroll_ - playlist_ex.scroll) > 0.01) {
            playlist_ex.scroll___ += (playlist_ex.scroll - playlist_ex.scroll___) * delta;
            playlist_ex.scroll__ += (playlist_ex.scroll___ - playlist_ex.scroll__) * delta;
            playlist_ex.scroll_ += (playlist_ex.scroll__ - playlist_ex.scroll_) * delta;
            al_ex = repaint_2 = true;
        } else if (playlist_ex) {
            playlist_ex.scroll____ = playlist_ex.scroll___ = playlist_ex.scroll__ = playlist_ex.scroll_ = playlist_ex.scroll;
        }

        if (playlist_ex && check_ex(m_x, m_y) != check_ex_old) {
            check_ex_old = check_ex(m_x, m_y);
            repaint_2 = true;
        }

        end = Math.min(end, list_dr.length);
        start = Math.max(0, start);
        var repaint_temp = repaint_2;
        //fb.trace("time_max_img : " + time_max_img)
        if (time_r.Time > time_reset_loadimg && Math.abs(scroll - scroll_) < postion_load_img * cell) {
            var repaint_temp = repaint_2,
                i = 0;
            if (Math.abs(scroll - scroll_) < 1 && !al_ex)
                end = list_dr.length;
            for (i = start; i < end; i++) {
                if (time_scroll.Time > 3) break;
                else if (list_dr[i].state == 3)
                    continue;
                else if (list_dr[i].state == 0) {
                    var tmp_ = load_image(list_dr[i].pl.Item(0), true);
                    list_dr[i].id = tmp_[0];
                    list_dr[i].string_cache = tmp_[1];
                    if (list_dr[i].id % 1 == 0.5) {
                        list_dr[i].img_ = list_img[Math.floor(list_dr[i].id)].img;
                        list_dr[i].state = 2;
                        i--;
                        continue;
                    } else if (list_dr[i].id == -1) {
                        list_dr[i].Time = fb.CreateProfiler();
                        list_dr[i].state = -1;
                    } else if (list_dr[i].id == 0) {
                        list_dr[i].state = 3;
                        continue;
                    } else if (list_dr[i].id == -1000) {
                        list_dr[i].img_ = tmp_[2];
                        list_dr[i].state = 3;
                        max_load_done = i;
                    } else {
                        repaint_2 = true;
                        time_r.Reset();
                        list_dr[i].state = 1;
                    }
                    break;
                } else if (list_dr[i].state == 2 && list_dr[i].img_) {
                    max_load_done = i;
                    list_dr[i].state = 3;
                    list_dr[i].imgcell = Draw_cell(list_dr[i].img_, list_dr[i].name + "\r\n(" + list_dr[i].pl.Count + " Tracks)");
                    repaint_2 = true;
                    break;
                } else if ((list_dr[i].state == -1 && list_dr[i].Time.Time > 400) || (list_dr[i].state < -1 && list_dr[i].Time.Time > 2000)) { //wait to load image from script
                    var tmp_ = load_image(list_dr[i].pl.Item(0), false);
                    list_dr[i].id = tmp_[0];
                    list_dr[i].string_cache = tmp_[1];
                    if (list_dr[i].id > 0) {
                        repaint_2 = true;
                        time_r.Reset();
                        list_dr[i].state = 1;
                        break;
                    } else {
                        list_dr[i].Time.Reset();
                        list_dr[i].state--;
                        if (list_dr[i].state < -6)
                            list_dr[i].state = 3;
                    }
                }
            }

        }
        if (Math.abs(scroll - scroll_) < 1) {
            repaint_2 = repaint_temp;
        }

        if (repaint_main1 == repaint_main2) {
            repaint_main2 = !repaint_main1;
            repaint_2 = true;
        }

    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

    if (repaint_1 && repaint_2) {
        repaint_f = true;
        repaint_main = true;
        window.Repaint();
    } else if (repaint_1) {
        repaint_f = true;
        window.RepaintRect(0, 0, ww, text_heigh);
    } else if (repaint_2) {
        repaint_main = true;
        window.RepaintRect(0, text_heigh, ww, wh - text_heigh);
    }
}

function repaint() {
    repaint_main1 = repaint_main2;
}

function read_list(reload) {
    list = [];
    read_library(reload);
}

function match(input, string) {
    var temp = "";
    input = input.toLowerCase();
    string = string.toLowerCase();
    while (input != (temp = input.replace("  ", " ")))
        input = temp;
    while (string != (temp = string.replace("  ", " ")))
        string = temp;
    var str = string.split(" ");
    for (var i in str) {
        if (str[i] == "" || input != (temp = input.replace(str[i], "")))
            input = temp;
        else
            return false;
    }
    return true;
}

function search(string) {
    list_dr = [];
    var back_s = -1.5;

    var bbb = Math.ceil(row_count * ww / cell / 2);
    for (var i in list) {
        if (match(list[i].name, string)) {
            back_s = list_dr.length;
            list_dr.push(list[i]);
            if (Math.abs(list[i].i - back_s) > row_count * (ww / cell / 2))
                list[i].al = 0;
        } else {
            list[i].i = (back_s - i < row_count) ? (back_s + 0.5) : i - row_count;
            list[i].al = 0;
        }
    }
    scroll___ = scroll__ = scroll_ = scroll = 0;
    repaint();

    ex_al_idx = -1000;
    var max_row_ex = Math.ceil(list_dr.length / row_count) + 1;
    for (var i = 0; i < max_row_ex; i++)
        ex_length_idx___[i] = ex_length_idx__[i] = ex_length_idx_[i] = ex_length_idx[i] = 0;

}


function check(x, y) {
    if (!mouse_in || y < text_heigh || y > wh - 7)
        return -1;
    var row = Math.floor((y - text_heigh - 4) / cell); //ex_al_idx
    var col = Math.floor((x + scroll_) / (cell * 2));

    var row_ex_idx = Math.floor(ex_al_idx / row_count);
    if (playlist_ex && (col == row_ex_idx + 1 || col == row_ex_idx + 2)) {
        //cell * 1.6 + y + 20*i - playlist_ex.scroll_ * 20;
        //playlist_ex
        var track_idx = Math.floor((y - (1.6 * cell + 20)) / 20 + playlist_ex.scroll_);
        if (track_idx > -1 && track_idx < playlist_ex.list.length) {
            return (-1.500 - track_idx / 1000);
        } else return -1.1;
    } else if (playlist_ex && ex_al_idx > -1 && col > row_ex_idx + 2) {
        col -= ex_length_idx[col];
    }
    if (row < 0 || row > row_count - 1)
        return -1;
    var index = row + row_count * col;
    if (index < list_dr.length && index >= 0) {
        return Math.floor(index);
    } else
        return -1;
}

//=========================================================================================== on mouse wheel
function on_mouse_wheel(step) {
    if (utils.IsKeyPressed(0x11)) {
        var scroll_t = Math.floor(scroll / cell / 2) * row_count;
        row_count -= step;
        row_count = Math.max(1, row_count);
        row_count = Math.min(10, row_count);
        window.SetProperty("Row", row_count);

        cell = Math.floor((wh - text_heigh - 12) / row_count);
        scroll____ = scroll__ = scroll_ = scroll = Math.round(scroll_t / row_count) * cell * scroll_step;
        max_scroll = scroll_ + ww;
        repaint_f1 = repaint_f2;
        repaint();
        return;
    } else if (check_ex(m_x, m_y) > -2) {
        scr_tmp = playlist_ex.scroll;
        scr_tmp -= step * scroll_step;
        scr_tmp = Math.min(scr_tmp, playlist_ex.list.length - playlist_ex.max_idx);
        scr_tmp = Math.max(0, scr_tmp);
        if (scr_tmp != playlist_ex.scroll) {
            playlist_ex.scroll = scr_tmp;
            return;
        } else if (playlist_ex.scroll != playlist_ex.scroll_) {
            return;
        }
    }
    scroll -= step * cell * scroll_step;
    var al_ex = 0;
    if (playlist_ex && playlist_ex.delta > 0) al_ex = playlist_ex.delta;
    //fb.trace(al_ex)
    if (scroll < 0 || Math.round(list_dr.length / row_count + 0.499 + al_ex) * (cell * 2) < ww)
        scroll = 0;
    if (scroll > max_scroll - ww)
        scroll = max_scroll - ww;
}

function check_ex(x, y) {
    var a = check(x, y);
    if (a <= -1.5)
        return Math.round((-a - 1.5) * 1000);
    else if (a == -1.1)
        return -1;
    else
        return -2;
}

//================================================================================ On mouse dbclk
var w = window.GetProperty("_DISPLAY: Wallpaper file #", 1);
var w_number = window.GetProperty("_DISPLAY: Number of Wallpapers", 46);

function on_mouse_lbtn_dblclk(x, y, mask) {
    var a = check(x, y);
    if (a > -1) {
        switch (list_dr[a].type) {
            case "pl":

                break;
            case "al":
                if (utils.IsKeyPressed(0x10)) {
                    w = window.GetProperty("_DISPLAY: Wallpaper file #");
                    w++;
                    if (w >= w_number) w = 1;
                    window.SetProperty("_DISPLAY: Default Wallpaper Path", ".\\themes\\bg\\" + w + ".jpg");
                    window.SetProperty("_DISPLAY: Wallpaper file #", w);
                    on_size();
                };
                else if (utils.IsKeyPressed(0x11)) {
                    def_dblclk_act = !def_dblclk_act;
                    window.SetProperty("Default Double Click Action ADD|APPLY", def_dblclk_act);
                    on_size();
                };
                else {
                    if (def_dblclk_act) {
                        add_playlist(list_dr[a].pl);
                    };
                    else {
                        apply_playlist(list_dr[a].pl);
                        //on_mouse_lbtn_down(x,y,mask);
                    };
                };

                break;
        }
    } else if (a <= -1.5) {
        var idx = Math.round((-a - 1.5) * 1000);
        if (playlist_ex) {
            apply_playlist(playlist_ex.pl, idx);
        }
    } else if (y < text_heigh && x < ww - text_heigh) {
        on_mouse_lbtn_down(x, y, 1.5);
    }
}
//==================================================================================//
var library_path_ = window.GetProperty("_SYS: Remove Library Path from Cell", "D:\\Music\\").split(";");

function read_library(reload) {
    var Time = fb.CreateProfiler("Time Load library");
    var TitleFormat = sorting_opt;
    var FoobarTitleFormat = fb.TitleFormat(TitleFormat);
    var pl_name = "",
        pl_idx = -1,
        list_;
    for (var i = 0; i < plman.PlaylistCount; i++) {
        pl_name = plman.GetPlaylistName(i);
        if (pl_name == "WSH Album Filter") {
            pl_idx = i;
            break;
        }
    }
    if (pl_idx < 0) {
        pl_idx = plman.PlaylistCount;
        fb.CreateAutoPlaylist(pl_idx, "WSH Album Filter", "ALL", TitleFormat);
        list_ = plman.GetPlaylistItems(pl_idx);
        plman.RemovePlaylist(pl_idx);
    } else if (reload) {
        plman.RemovePlaylist(pl_idx);
        fb.CreateAutoPlaylist(pl_idx, "WSH Album Filter", "ALL", TitleFormat);
        list_ = plman.GetPlaylistItems(pl_idx);
        plman.RemovePlaylist(pl_idx);
    } else
        list_ = plman.GetPlaylistItems(pl_idx);
    var string_compare = "123456789123456789",
        string = "",
        k = 0,
        i = 0,
        item, count = 0;
    var a = "",
        b = "",
        tmp, total = list_.Count;
    Time.print();
    Time.Reset();
    while (k < total) {
        string = FoobarTitleFormat.EvalWithMetadb(list_.Item(k));

        for (var j = 0; j < library_path_.length; j++)
            string = string.replace(library_path_[j], "");

        tmp = string.split("^^");


        a = fb.TitleFormat("$if2(%artist%,$if(%length%,%_directoryname%,%path%))").EvalWithMetadb(list_.Item(k));
        b = tmp[1];
        if (a.length < 3) {
            k++;
            continue;
        }
        if (string_compare != string) {
            string_compare = string;
            item = new Object();
            item.name = a + "\r\n" + b;
            item.type = "al";
            item.al = 255;
            item.i = list.length - 3;
            item.i_ = item.i;
            item.alpha = 0;
            item.state = 0;
            item.id = 0;
            item.img = null;
            item.pl = plman.GetPlaylistItems(-1);
            item.pl.Add(list_.Item(k));
            count = 1;
            (min_song == 1) && list.push(item);
        } else {
            count++;
            item.pl.Add(list_.Item(k));
            if (count == min_song)
                list.push(item);
        }
        k++;
    }
    time_scroll.Reset();
    Time.print();
}

//=================================================== add apply to playlist
function apply_playlist(playlist, start) {
    var pl_idx = check_playlist("Library view");
    if (pl_idx == -1) {
        pl_idx = plman.PlaylistCount;
        plman.CreatePlaylist(pl_idx, "Library view");
    } else
        fb.RunMainMenuCommand("Edit/Clear");
    plman.ActivePlaylist = pl_idx;
    var playlist_ = playlist.Clone();
    !start && playlist_.OrderByFormat(fb.TitleFormat("%path%"), 1);
    plman.InsertPlaylistItems(pl_idx, 1, playlist_);
    plman.ExecutePlaylistDefaultAction(pl_idx, start ? start : 0);
    fb.RunMainMenuCommand("Edit/Remove Duplicates");
}

function add_playlist(playlist) {
    var pl_idx = check_playlist("Library view");
    if (pl_idx == -1) {
        pl_idx = plman.PlaylistCount;
        plman.CreatePlaylist(pl_idx, "Library view");
    };
    plman.ActivePlaylist = pl_idx;
    playlist.OrderByFormat(fb.TitleFormat("%path%"), 1);
    plman.InsertPlaylistItems(plman.ActivePlaylist, 0, playlist);
    plman.ExecutePlaylistDefaultAction(pl_idx, 0);
    fb.RunMainMenuCommand("Edit/Remove Duplicates");
}

function on_mouse_mbtn_up(x, y, mask) {
    var a = check(x, y);
    if (a > -1) {
        switch (list_dr[a].type) {
            case "pl":
                break;
            case "al":
                add_playlist(list_dr[a].pl);
                break;
        }
    }
}

var textrender = gdi.CreateStyleTextRender();
textrender.EnableShadow(true);
textrender.GlowText(g_text_color, g_text_glow_color, text_glow_color_width);
textrender.DiffusedShadow(g_text_shadow_color, 1, 1, 1);

//=============================================================Album Art Cell 
function Draw_cell(image, string) {
    if (cell_null ? (cell_null.Width != cell * 2 - 3) : true)
        install_cell();
    var tmp_img = cell_null.Clone(0, 0, cell * 2 - 3, cell - 3);
    var gp = tmp_img.GetGraphics();
    gp.SetTextRenderingHint(3);
    gp.SetSmoothingMode(4);
    gp.SetInterpolationMode(7);
    image && gp.DrawImage(image, 3, 2, cell + 15, cell - 7, 0, 0, image.Width, image.Height, 0, 255);
    textrender.RenderStringRect(gp, string, g_font_c, cell + 35, 10, cell - 40, cell, 0);
    textrender.ResetShadow();
    return DrawBitmap ? tmp_img.CreateRawBitmap() : tmp_img;
}

function on_load_image_done(tid, image) {
    for (var i in list) {
        if (!list[i].id) continue;
        if (list[i].id == tid && list[i].state == 1) {
            list[i].state = 2;
            list[i].img_ = image;
            repaint_main1 = repaint_main2;
            var img_cache = new Object();
            img_cache.img = image;
            img_cache.string = list[i].string_cache;
            list_img.push(img_cache);
            break;
        }
    }
}

var notifi_nostub_img = false;

//================================================================= inst cell
function install_cell() {
    try {
        stub_image = gdi.Image(window.GetProperty("Stub_Image_Path", ".\\themes\\album_stub.png"));
    } catch (err) {
        stub_image = null;
    }
    cell_null = gdi.CreateImage(cell * 2 - 3, cell - 3);
    var gp = cell_null.GetGraphics();
    gp.SetTextRenderingHint(3);
    gp.SetSmoothingMode(4);
    gp.SetInterpolationMode(7);
    gp.FillGradRect(0, 0, cell * 2 - 3, cell - 3, select_angle2, g_cover_back_color, g_back_shadow_color, 1);
    if (!stub_image_gliph) {
        stub_image && gp.DrawImage(stub_image, 1, 1, cell - 5, cell - 5, 0, 0, stub_image.Width, stub_image.Height, 0, 255);
    } else {
        gp.DrawString(no_cover_gliph, g_font_gliph, g_no_cover_gliph_color, cell / 2 - font_gliph_size / 2, cell / 2 - font_gliph_size / 2, cell * 2 - 3, cell - 3, 0);
    };
    cell_null.ReleaseGraphics(gp);
    cell_null_gr = DrawBitmap ? cell_null.CreateRawBitmap() : cell_null;
}

function on_mouse_rbtn_up(x, y) {
    var MF_SEPARATOR = 0x00000800;
    var MF_STRING = 0x00000000;
    var _menu = window.CreatePopupMenu();
    var _menu1 = window.CreatePopupMenu();
    var Context = fb.CreateContextMenuManager();
    var idx;
    if (y < text_heigh) {
        (form_his.length > 0) && _menu.AppendMenuItem(MF_STRING, 1, "Undo  ");
        (form_his_.length > 0) && _menu.AppendMenuItem(MF_STRING, 2, "Redo  ");
        (bold_start != bold_end) && _menu.AppendMenuItem(MF_STRING, 3, "Coppy ");
        (bold_start != bold_end) && _menu.AppendMenuItem(MF_STRING, 4, "Cut   ");
        (htmlfile.parentWindow.clipboardData.getData('text') != null) && _menu.AppendMenuItem(MF_STRING, 5, "Paste ");
    } else {
        var check__ = check(x, y);
        if (check__ > -1) {
            Context.InitContext(list_dr[check__].pl);
            Context.BuildMenu(_menu, 100, -1);
            on_mouse_move(x, y);
        }
    }
    _menu1.AppendMenuItem(MF_STRING, 8, "Refresh library");
    _menu1.AppendMenuItem(MF_STRING, 9, "Show Wallpaper");
    _menu1.AppendMenuItem(MF_STRING, 10, "Show Blur");
    _menu1.AppendMenuItem(MF_STRING, 11, "Wallpaper Mode Art|Pic");
    _menu1.AppendMenuSeparator();
    _menu1.AppendMenuItem(MF_STRING, 7, "Show Properties");
    _menu1.AppendMenuItem(MF_STRING, 6, "Show Script...");
    _menu.AppendMenuSeparator();
    _menu1.AppendTo(_menu, MF_STRING, "Preferences");
    _menu1.CheckMenuItem(9, ppt.showwallpaper);
    _menu1.CheckMenuItem(10, ppt.wallpaperblurred);
    _menu1.CheckMenuItem(11, ppt.wallpapermode);
    idx = _menu.TrackPopupMenu(x, y);
    switch (idx) {
        case 0:
            break;
        case 1:
            on_char(26);
            break;
        case 2:
            on_char(25);
            break;
        case 3:
            on_char(3);
            break;
        case 4:
            on_char(24);
            break;
        case 5:
            on_char(22);
            break;
        case 6:
            window.ShowConfigure();
            break;
        case 7:
            window.ShowProperties();
            break;
        case 8:
            read_list(true);
            search(form_text);
            break;
        case 9:
            ppt.showwallpaper = !ppt.showwallpaper;
            window.SetProperty("_DISPLAY: Show Wallpaper", ppt.showwallpaper);
            on_size();
            break;
        case 10:
            ppt.wallpaperblurred = !ppt.wallpaperblurred;
            window.SetProperty("_DISPLAY: Wallpaper Blurred", ppt.wallpaperblurred);
            on_size();
            break;
        case 11:
            ppt.wallpapermode = !ppt.wallpapermode;
            window.SetProperty("_DISPLAY: Wallpaper Mode", ppt.wallpapermode);
            on_size();
            break;
        default:
            (idx > 0) && Context.ExecuteByID(idx - 100);
            break;
    }
    Context.Dispose();
    _menu.Dispose();
    return true;
}

function check_playlist(name) {
    var pl_name = "",
        pl_idx = -1;
    for (var i = 0; i < plman.PlaylistCount; i++) {
        pl_name = plman.GetPlaylistName(i);
        if (pl_name == name) {
            pl_idx = i;
            break;
        }
    }
    return pl_idx;
}

function getpath(path) {
    var img_path = "";
    var path_, temp, subFlds, tmp;
    for (var iii = 0; iii < 2; iii++) {
        if (tmp = getpath_(iii == 0 ? path : (path + "..\\")))
            return tmp;
        try {
            subFlds = new Enumerator(fso.GetFolder((iii == 0 ? path : (path + "..\\"))).SubFolders);
        } catch (err) {
            return null
        };
        for (; !subFlds.atEnd(); subFlds.moveNext()) {
            temp = subFlds.item() + "\\";
            if (temp.toLowerCase().match(cover_path)) {
                if (tmp = getpath_(temp))
                    return tmp;
            }
        }
    }
    return null;
}

function getpath_(temp) {
    var img_path = "",
        path_;
    for (var iii in cover_img) {
        path_ = utils.Glob(temp + cover_img[iii]).toArray();
        for (var j in path_) {
            if (path_[j].toLowerCase().indexOf(".jpg") > -1 || path_[j].toLowerCase().indexOf(".png") > -1 || path_[j].toLowerCase().indexOf(".gif") > -1) {
                return path_[j];
            }
        }
    }
    return null;
}

function load_imagecache(string) {
    for (var i = 0; i < list_img.length; i++) {
        if (list_img[i].string == string)
            return i;
    }
    return -1;
}


function load_image(metadb, first, path_) {
    if (!path_) {
        var tran = false;
        var path = fb.TitleFormat("$directory_path(%path%)\\").EvalWithMetadb(metadb);
        path_ = getpath(path);
        if (!path_)
            path_ = getpath_(fb.FoobarPath + "cache\\artist_pic\\" + fb.TitleFormat("[%artist%]\\").EvalWithMetadb(metadb));
        if (!path_) {
            return 0;
        }
    }

    var string = processpath(path_),
        tmp = load_imagecache(string);

    if (tmp > -1) {
        time_reset_loadimg = 0;
        return Array(tmp + 0.5, string);
    } else if (fso.FileExists(fb.FoobarPath + "cache\\album\\" + string)) { //Image cache
        time_reset_loadimg = 0;
        if (Load_async)
            return Array(gdi.LoadImageAsync(window.ID, fb.FoobarPath + "cache\\album\\" + string), string);
        else {
            var img = gdi.Image(fb.FoobarPath + "cache\\album\\" + string);
            var img_cache = new Object();
            img_cache.img = img;
            img_cache.string = string;
            list_img.push(img_cache);
            return Array(-1000, string, img);
        }
    } else if (first && fso.FileExists(path_)) { //jscript resize and save image cache
        var comm = "wscript //E:jscript \"" + fb.FoobarPath + "cache\\LoadIMG.js\" \"" + fb.FoobarPath + "\" \"" + path_ + "\" \"" + string + "\" \"" + tran + "\"";
        WshShell.Run(comm, false, false);
        time_reset_loadimg = 150;
        return Array(-1, string);
    }
    return Array(0, string);
}

function processpath(path) {
    var str_return = "";
    path = path.toLowerCase();
    var length = path.length;
    for (var i = 0; i < length; i++) {
        var charcode = path.charCodeAt(i);
        if (charcode > 96 && charcode < 123)
            str_return += path.charAt(i);
        else if (charcode > 47 && charcode < 58)
            str_return += path.charAt(i);
        else if (charcode == 46)
            str_return += path.charAt(i);
    }
    return str_return;
}

var nowmetadb = null;

function on_load() {
    //read_list(true);
    //search(form_text);
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    if(!fso.FolderExists(fb.FoobarPath + "cache"))
        fso.CreateFolder(fb.FoobarPath + "cache");
    if(!fso.FolderExists(fb.FoobarPath + "cache\\album"))
        fso.CreateFolder(fb.FoobarPath + "cache\\album");
    if(!fso.FileExists(fb.FoobarPath + "cache\\LoadIMG.js")){
        var data = "var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\r\n"
         + "var Img = new ActiveXObject(\"WIA.ImageFile.1\");\r\n"
         + "var IP = new ActiveXObject(\"WIA.ImageProcess.1\");\r\n"
         + "IP.Filters.Add(IP.FilterInfos(\"Scale\").FilterID);//ID = 1\r\n"
         + "IP.Filters.Add(IP.FilterInfos(\"Crop\").FilterID);//ID = 2\r\n"
         + "IP.Filters.Add(IP.FilterInfos(\"Convert\").FilterID);//ID = 3\r\n"
         + "function resize_image(path,string,tranparent)\r\n"
         + "{\r\n"
         + "    var cachesize = 200;\r\n"
         + "    var img_w = cachesize,img_h = cachesize,cr_x = 0,cr_y = 0;\r\n"
         + "    try{\r\n"
         + "    Img.LoadFile(path);\r\n"
         + "    }catch(err){\r\n"
         + "		return false;\r\n"
         + "    }\r\n"
         + "    if (Img.Width > Img.Height){\r\n"
         + "        img_w *= Img.Width / Img.Height;\r\n"
         + "        cr_x = (img_w - img_h)/2;\r\n"
         + "    }else {  \r\n"
         + "        img_h *= Img.Height / Img.Width;\r\n"
         + "        cr_y = (img_h - img_w)/2;\r\n"
         + "    }\r\n"
         + "    IP.Filters(1).Properties(\"MaximumWidth\") = img_w;\r\n"
         + "    IP.Filters(1).Properties(\"MaximumHeight\") = img_h;\r\n"
         + "    if(tranparent == \"true\"){\r\n"
         + "        IP.Filters(3).Properties(\"FormatID\").Value = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}';\r\n"
         + "    }else{\r\n"
         + "        IP.Filters(3).Properties(\"FormatID\").Value = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';\r\n"
         + "        IP.Filters(3).Properties(\"Quality\").Value = 80; \r\n"
         + "    }\r\n"
         + "    IP.Filters(2).Properties(\"Left\") = cr_x;\r\n"
         + "    IP.Filters(2).Properties(\"Top\") = cr_y;\r\n"
         + "    IP.Filters(2).Properties(\"Right\") = cr_x;\r\n"
         + "    IP.Filters(2).Properties(\"Bottom\") = cr_y;\r\n"
         + "    Img = IP.Apply(Img);\r\n"
         + "    try{\r\n"
         + "        if(fso.FileExists(WScript.arguments(0) + \"cache\\\\album\\\\\" + string))\r\n"
         + "            fso.DeleteFile(WScript.arguments(0)+ \"cache\\\\album\\\\\" + string);\r\n"
         + "        Img.SaveFile(WScript.arguments(0) + \"cache\\\\album\\\\\" + string);\r\n"
         + "    }catch(err){\r\n"
         + "		return false;\r\n"
         + "    }\r\n"
         + "	return true;\r\n"
         + "}\r\n"
         + "resize_image(WScript.arguments(1),WScript.arguments(2),WScript.arguments(3));";
        var file = fso.CreateTextFile(fb.FoobarPath + "cache\\LoadIMG.js", true,65001);
        file.WriteLine(data);
        file.Close();
    }

}

on_load();
window.ClearTimeout(t____);
var t____ = window.SetTimeout(function() {
    read_list();
    search("");

}, load_lib_timeout);

var t_to_refresh = false;
function on_library_items_added() {
    window.ClearTimeout(t_to_refresh);
    t_to_refresh = window.SetTimeout(function() {
        read_list(true);
        search(form_text);
    }, time_to_refresh_on_add_rem);
};
var t_to_refresh2 = false;
function on_library_items_removed() {
    window.ClearTimeout(t_to_refresh2);
    t_to_refresh2 = window.SetTimeout(function() {
        read_list(true);
        search(form_text);
    }, time_to_refresh_on_add_rem);
};

function setWallpaperImg(path, metadb) {
    var fmt_path = fb.TitleFormat(path).Eval(true);
    var fmt_path_arr = utils.Glob(fmt_path).toArray();
    if (fmt_path_arr.length > 0) {
        var final_path = fmt_path_arr[0];
    };
    else {
        var final_path = null;
    };

    if (metadb && ppt.wallpapermode == 0) {
        var tmp_img = utils.GetAlbumArtV2(metadb, ppt.wallpapermode);
    };
    else {
        if (final_path) {
            tmp_img = gdi.Image(final_path);
        };
        else {
            tmp_img = null;
        };
    };
    if (!tmp_img) {
        if (final_path) {
            tmp_img = gdi.Image(final_path);
        };
        else {
            tmp_img = null;
        };
    };

    g_wallpaperImg = null;
    var img = FormatWallpaper(tmp_img, ww, wh, 2, 0, 0, "", true);
    return img;
};

function draw_blurred_image(image, ix, iy, iw, ih, bx, by, bw, bh, blur_value, overlay_color) {
    var blurValue = blur_value;
    var imgA = image.Resize(iw * blurValue / 100, ih * blurValue / 100, 2);
    var imgB = imgA.resize(iw, ih, 2);
    var overlay_color = RGBA(0, 0, 0, ppt.wallpaperoverlayalfa); //50);

    var bbox = gdi.CreateImage(bw, bh);
    // Get graphics interface like "gr" in on_paint
    var gb = bbox.GetGraphics();
    var offset = 90 - blurValue;
    gb.DrawImage(imgB, 0 - offset, 0 - (ih - bh) - offset, iw + offset * 2, ih + offset * 2, 0, 0, imgB.Width, imgB.Height, 0, 255);
    bbox.ReleaseGraphics(gb);

    var newImg = gdi.CreateImage(iw, ih);
    var gb = newImg.GetGraphics();

    if (ix != bx || iy != by || iw != bw || ih != bh) {
        gb.DrawImage(image, ix, iy, iw, ih, 0, 0, image.Width, image.Height, 0, 255);
        gb.FillSolidRect(bx, by, bw, bh, 0xffffffff);
    };
    gb.DrawImage(bbox, bx, by, bw, bh, 0, 0, bbox.Width, bbox.Height, 0, 255);

    // overlay
    if (overlay_color != null) {
        gb.FillSolidRect(bx, by, bw, bh, overlay_color);
    };

    // top border of blur area
    if (ix != bx || iy != by || iw != bw || ih != bh) {
        gb.FillSolidRect(bx, by, bw, 1, 0x22ffffff);
        gb.FillSolidRect(bx, by - 1, bw, 1, 0x22000000);
    };
    newImg.ReleaseGraphics(gb);

    return newImg;
};

function FormatWallpaper(image, iw, ih, interpolation_mode, display_mode, angle, txt, rawBitmap) {
    if (!image || !iw || !ih) return image;
    var i, j;

    var panel_ratio = iw / ih;
    wpp_img_info.ratio = image.Width / image.Height;
    wpp_img_info.orient = 0;

    if (wpp_img_info.ratio > panel_ratio) {
        wpp_img_info.orient = 1;
        // 1/3 : default image is in landscape mode    
        switch (display_mode) {
            case 0: // Filling
                //wpp_img_info.w = iw * wpp_img_info.ratio / panel_ratio;
                wpp_img_info.w = ih * wpp_img_info.ratio;
                wpp_img_info.h = ih;
                wpp_img_info.cut = wpp_img_info.w - iw;
                wpp_img_info.x = 0 - (wpp_img_info.cut / 2);
                wpp_img_info.y = 0;
                break;
            case 1: // Adjust
                wpp_img_info.w = iw;
                wpp_img_info.h = ih / wpp_img_info.ratio * panel_ratio;
                wpp_img_info.cut = ih - wpp_img_info.h;
                wpp_img_info.x = 0;
                wpp_img_info.y = wpp_img_info.cut / 2;
                break;
            case 2: // Stretch
                wpp_img_info.w = iw;
                wpp_img_info.h = ih;
                wpp_img_info.cut = 0;
                wpp_img_info.x = 0;
                wpp_img_info.y = 0;
                break;
        };
    };
    else if (wpp_img_info.ratio < panel_ratio) {
        wpp_img_info.orient = 2;
        // 2/3 : default image is in portrait mode
        switch (display_mode) {
            case 0: // Filling
                wpp_img_info.w = iw;
                //wpp_img_info.h = ih / wpp_img_info.ratio * panel_ratio;
                wpp_img_info.h = iw / wpp_img_info.ratio;
                wpp_img_info.cut = wpp_img_info.h - ih;
                wpp_img_info.x = 0;
                wpp_img_info.y = 0 - (wpp_img_info.cut / 4);
                break;
            case 1: // Adjust
                wpp_img_info.h = ih;
                wpp_img_info.w = iw * wpp_img_info.ratio / panel_ratio;
                wpp_img_info.cut = iw - wpp_img_info.w;
                wpp_img_info.y = 0;
                wpp_img_info.x = wpp_img_info.cut / 2;
                break;
            case 2: // Stretch
                wpp_img_info.w = iw;
                wpp_img_info.h = ih;
                wpp_img_info.cut = 0;
                wpp_img_info.x = 0;
                wpp_img_info.y = 0;
                break;
        };
    };
    else {
        // 3/3 : default image is a square picture, ratio = 1
        wpp_img_info.w = iw;
        wpp_img_info.h = ih;
        wpp_img_info.cut = 0;
        wpp_img_info.x = 0;
        wpp_img_info.y = 0;
    };

    var tmp_img = gdi.CreateImage(iw, ih);
    var gp = tmp_img.GetGraphics();
    gp.SetInterpolationMode(interpolation_mode);
    gp.DrawImage(image, wpp_img_info.x, wpp_img_info.y, wpp_img_info.w, wpp_img_info.h, 0, 0, image.Width, image.Height, angle, ppt.wallpaperalfa); //255);
    tmp_img.ReleaseGraphics(gp);

    // blur it!
    if (ppt.wallpaperblurred) {
        var blur_factor = ppt.wallpaperblurvalue; // [1-90]
        tmp_img = draw_blurred_image(tmp_img, 0, 0, tmp_img.Width, tmp_img.Height, 0, 0, tmp_img.Width, tmp_img.Height, blur_factor, 0x00ffffff);
    };

    CollectGarbage();
    if (rawBitmap) {
        return tmp_img.CreateRawBitmap();
    };
    else {
        return tmp_img;
    };
};

function on_playback_new_track(metadb) {
    g_metadb = metadb;
    if (ppt.showwallpaper) {
        g_wallpaperImg = setWallpaperImg(ppt.wallpaperpath, metadb);
    };
    repaint_f1 = repaint_f2;
    repaint_main1 = repaint_main2;
};